/**
 * 数据请求
 */
import http from '@ohos.net.http';
import { Constants } from '../common/Constants';
import { Log } from '../common/Log';
import promptAction from '@ohos.promptAction';
import { News } from './News';

class HttpRequest {
  instance: http.HttpRequest;

  constructor() {
    this.instance = http.createHttp();
  }

  post = (url: string, col: number, page: number): Promise<Array<News>> => {
    Log.info(`request: ${Constants.SERVER_URL}/${url}?col=${col}&page=${page}`);
    return new Promise((resolve, reject) => {
      this.instance.request(`${Constants.SERVER_URL}/${url}`, {
        method: http.RequestMethod.GET,
        extraData: {
          "key": "04dc9e1ef3a8b6308f640331d81e032c",
          "num": "10",
          "col": col.toString(),
          "page": page.toString()
        }
      }).then((ret) => {
        Log.info(`response: ${JSON.stringify(ret)}`);
        if (ret.responseCode === http.ResponseCode.OK) {
          let data = JSON.parse(ret.result as string);
          if (data.code === 200) {
            let news: Array<News> = data.result['newslist'];
            resolve(news);
          } else {
            promptAction.showToast({
              message: data.msg
            })
          }
        } else {
          promptAction.showToast({
            message: "服务器开小差了，请稍后尝试！"
          })
        }
      }).catch((err) => {
        Log.error(`request faild: ${JSON.stringify(err)}`);
        promptAction.showToast({
          message: "请求异常，请检查网络后再次尝试！"
        })
      })
    });
  }
}

export const HttpUtil = new HttpRequest();